<section class="flat-shop-cart">
	<div class="container">
		<div class="row">
			<div class="col-lg-8">
				<div class="flat-row-title style1">
					<h3>购物车中商品列表</h3>
				</div>
				<div class="table-cart">
					<table>
						<thead>
							<tr>
								<th>商品名称</th>
								<th>数量</th>
								<th>总额</th>
								<th></th>
							</tr>
						</thead>
						<tbody id="cart_item_container"></tbody>
					</table>
				</div><!-- /.table-cart -->
			</div><!-- /.col-lg-8 -->
			<div class="col-lg-4">
				<div class="cart-totals">
					<h3>购物车汇总</h3>
					<form action="#" method="get" accept-charset="utf-8">
						<table>
							<tbody>
								<tr>
									<td>小计</td>
									<td class="subtotal" id="td_cart_itemprice"></td>
								</tr>
								<tr>
									<td>运费</td>
									<td class="btn-radio">
										<div class="radio-info">
											<label for="flat-rate"><span id="span_shipping_count" price=10>￥10</span></label>
										</div>
									</td><!-- /.btn-radio -->
								</tr>
								<tr>
									<td>总计</td>
									<td class="price-total" id="td_cart_pricetotal" total_price=0></td>
								</tr>
								<tr>
									<td>地址</td>
									<td>
										<ldbz:current_user_tag attr="id" ;user>
											<%if(user=="false"){%>
												请先<a href="${request.contextPath}/sso/login?returnUrl=${request.contextPath}/cart" >【登录】</a>后维护默认地址
											<%}else{%>
												<ldbz:default_address_tag userId="${user}" ; address>
													<%if(address==null){%>
														<a id="a_select_default_addr" href="javascript:;">请先维护默认地址</a>
													<%}else{%>
														<p id="p_addr">${address.userAddress}</p>
														<a id="a_select_addr" href="javascript:;">选择其他地址</a>
													<%}%>
												</ldbz:default_address_tag>
											<%}%>
										</ldbz:current_user_tag>
									</td>
								</tr>
							</tbody>
						</table>
						<div class="btn-cart-totals">
							<a id="a_pay_now" href="javascript:;" class="checkout" >立即支付</a>
						</div><!-- /.btn-cart-totals -->
					</form><!-- /form -->
				</div><!-- /.cart-totals -->
			</div><!-- /.col-lg-4 -->
		</div><!-- /.row -->
	</div><!-- /.container -->
</section>

<script id="cart_item_template" type="text/html">
{{each $data as item i}}
	<tr>
		<td title="{{item.item_title}}">
			<div class="img-product">
				<a  href="${request.contextPath}/item/{{item.item_code}}" title="" target="_blank"><img src="${nginxImage}{{item.item_image}}" alt=""></a>
			</div>
			<div class="name-product" style="padding-top:18px;width:170px;overflow:hidden; white-space:nowrap; text-overflow:ellipsis">{{item.item_title}}</div>
			<div class="price">￥{{item.item_price}}</div>
			<div class="clearfix"></div>
		</td>
		<td>
			<div class="quanlity">
				<span class="btn-down" name="span_btn_down" item_code="{{item.item_code}}"></span>
				<input id="input_{{item.item_code}}" type="text" name="number" value="{{item.count}}" min="1" max="100" placeholder="数量" readonly=true >
				<span class="btn-up" name="span_btn_up" item_code="{{item.item_code}}"
					item_title="{{item.item_title}}" item_price="{{item.item_price}}" item_image="{{item.item_image}}"></span>
			</div>
		</td>
		<td>
			<div class="total" name="div_item_total" price="{{(item.item_price * item.count).toFixed(2)}}">￥{{(item.item_price * item.count).toFixed(2)}}</div>
		</td>
		<td>
			<a href="javascript:;" title="删除商品" name="a_del_item" item_code="{{item.item_code}}">
				<img src="${request.contextPath}/cart/images/icons/delete.png" alt="">
			</a>
		</td>
	</tr>
{{/each}}
</script>
<script>
var addressWin = null ;

$(function(){
	
	var showCartList = function(){
		
		var _cart = getCookie("_cart");
		if(_cart){
			_cart = Base64.decode(_cart);
			var arr = $.parseJSON(_cart);
			$("#cart_item_container").html(template('cart_item_template', arr));
			
			var item_price_total = 0;
			var item_price = $("div[name='div_item_total']");
			$(item_price).each(function(i , o){
				item_price_total += ($(o).attr("price")*1); 
			})
			//小计
			$("#td_cart_itemprice").text("￥"+item_price_total.toFixed(2));
			//总计
			var total_price = (item_price_total+$("#span_shipping_count").attr("price")*1).toFixed(2) ;
			$("#td_cart_pricetotal").text("￥" + total_price);
			$("#td_cart_pricetotal").attr("total_price" , total_price);
			
			//计数器加一
			$("span[name='span_btn_up']").click(function(){
				var input_item_count = $(this).prev().val();
				if(input_item_count<100){
					$(this).prev().val(input_item_count*1+1);

	        		var item_code = $(this).attr("item_code") ;
	        		var item_title = $(this).attr("item_title") ;
	        		var item_price = $(this).attr("item_price") ;
	        		var item_image = $(this).attr("item_image") ;
	    			$(arr).each(function(i , o){
	    				if(item_code == o.item_code){
	    					//已经在购物车里面
	    					arr.splice(i , 1);
	    					arr.unshift({'item_code':item_code , 'item_title':item_title , 'item_price':item_price , 'item_image':item_image,'count':o.count*1+1});
	    				}
	    			});
	    			
	    			setCookie("_cart" , Base64.encode(JSON.stringify(arr)));
	    			jqueryAlert({
						'icon'    : '${request.contextPath}/cart/alert/img/right.png',
						'content' : '商品数量加一',
						'closeTime' : 2000,
					}).show();
	    			
	        		//显示购物车中的商品数量变化
	        		if(arr.length>0){
	        			var item_count = 0 , item_price = 0 ;
	        			$(arr).each(function(i , o){
	        				item_count += (o.count*1) ;
	        				item_price += (o.item_price*o.count) ;
	        			});
	        			$("#span_cart_itemcount").text(item_count).show();
	        		}else{
	        			$("#span_cart_itemcount").text('').hide();
	        		}
	    			showCartList();
	    			
				}else{
					jqueryAlert({
					    'icon'    : '${request.contextPath}/cart/alert/img/warning.png',
					    'content' : '商品最大100个',
					    'closeTime' : 2000,
					}).show();
				}
			});
			//计数器减一
			$("span[name='span_btn_down']").click(function(){
				var item_code = $(this).attr("item_code");
				var input_item_count = $(this).next().val();
				if(input_item_count>1){
					$(this).next().val(input_item_count*1-1);
				}else{
					jqueryAlert({
					    'icon'    : '${request.contextPath}/cart/alert/img/warning.png',
					    'content' : '如需清零，请点击删除按钮',
					    'closeTime' : 2000,
					}).show();
				}
			});
			//移除商品
			$("a[name='a_del_item']").click(function(){
				var item_code = $(this).attr("item_code");
				var delItemDialog = jqueryAlert({
				    'content' : "确定删除所选商品" ,
				    'modal'   : true,
				    'contentTextAlign' : 'left',
				    'width'   : '200px',
				    'animateType' : 'linear',
				    'buttons' :{
				        '取消' : function(){
				        	delItemDialog.close();
				        },
				        '确定' : function(){
				        	$(arr).each(function(i , o){
								if(o.item_code == item_code){
									if(o.count == 1){
										arr.splice(i , 1);
									}else{
										o.count = o.count-1;
									}
								}
							});
							setCookie("_cart" , Base64.encode(JSON.stringify(arr)));
							showCartItems();
							showCartList();
				        	delItemDialog.close();
				        }
				    }
				});
				delItemDialog.show();
			});
			
		}
		
	}
	
	showCartList();
	
	//维护默认地址
	$("#a_select_default_addr").click(function(){
		editAddress();
	});
	
	//改变默认地址
	$("#a_select_addr").click(function(){
		editAddress();
	});
	
	//立即支付
	$("#a_pay_now").click(function(){
		var addr_info = $("#p_addr").text();
		var total_price = $("#td_cart_pricetotal").attr("total_price");
		
		var items = null ;
		var _cart = getCookie("_cart");
		if(_cart){
			_cart = Base64.decode(_cart);
			items = $.parseJSON(_cart);
		}
		
		console.log(addr_info , total_price , items);
		
	});
	
});



var editAddress = function(){
	var li = "";
	$.ajax({
		contentType: 'application/x-www-form-urlencoded',
		url: '${request.contextPath}/cart/address/selectByEntity',
		method: 'post',
		async : false ,
		success:function(ret){
			if(ret.status==200 && ret.data && ret.data.length>0){
				$(ret.data).each(function(i , o){
					var isDefault = "" , setDefault="";
					if(o.isDefault){
						isDefault = "text-success";
					}else{
						setDefault='<a href="javascript:;" onclick="updateDefaultById(this)" title="设置为默认地址" addr_id='+o.id+' addr_info="'+o.userAddress+'"><p class="pull-right text-primary" style="margin-right:10px;"><i class="fa fa-map-signs" aria-hidden="true"></i></p></a>';
					}
					li += ('<li class="list-group-item" style="display:block;">'+
						'<p class="'+isDefault+' pull-left">'+o.userAddress+'</p>' +
						'<a href="javascript:delAddrByid('+o.id+');" ><p class="text-danger pull-right" style="font-size:16px;"><i class="fa fa-trash-o" aria-hidden="true"></i></p></a>'+setDefault+
						'</li>');
				});
			}
		},
		error:function(ret){
		}
	});
	var html = '<ul class="list-group">'+
				        '<li class="list-group-item" style="display:block;">'+
						'	<a id="a_add_addr" href="javascript:addAddressFunc();"><p class="text-warning pull-left">新建地址信息</p></a>'+
						'</li>'+ li
				    '</ul>';
	addressWin = jqueryAlert({
		'style'   : 'pc',
		'title'   : '地址维护',
		'content' :  html ,
		'modal'   : true,
		'contentTextAlign' : 'center',
		'width'   : '90%',
		'height'  : '90%',
		'animateType': 'scale',
		'bodyScroll' : 'true',
		'buttons' : {
			'关闭' : function(){
				addressWin.close();
			}
		}
	});
	addressWin.show();
}

//新建邮寄地址
var addAddressFunc = function(){
	addressWin.close();
	var addAddressWin = jqueryAlert({
		'style'   : 'pc',
		'title'   : '新建地址',
		'content' :  "<textarea id='textarea_address' style='height:100px;margin-top:5px;'></textarea> 设置为默认：<input id='input_check_default' style='opacity:1;' type='checkbox' />" ,
		'modal'   : true,
		'width'   : '400',
		'height'  : '230',
		'contentTextAlign' : 'center',
		'animateType': 'scale',
		'buttons' : {
			'关闭' : function(){
				addAddressWin.close();
			},
			'确定' : function(){

				var textarea_address = $("#textarea_address").val();
				var input_check_default = $("#input_check_default").is(":checked"); 
				
				$.ajax({
					contentType: 'application/x-www-form-urlencoded',
					url: '${request.contextPath}/cart/address/insertByEntity',
					method: 'post',
					data:{
						userAddress : textarea_address 
						,isDefault : input_check_default?1:0
					},
					success:function(ret){
						if(ret.status==200){
							addAddressWin.close();
							editAddress();
						}
					},
					error:function(ret){
					}
				});
			}
		}
	});
}

var delAddrByid = function(id){

	var delWarn = jqueryAlert({
		'title'   : '系统提示',
		'content' : "是否删除所选的记录？" ,
		'modal'   : true,
		'contentTextAlign' : 'left',
		'animateType' : 'linear',
		'buttons' :{
			'确定' : function(){
				$.ajax({
					contentType: 'application/x-www-form-urlencoded',
					url: '${request.contextPath}/cart/address/deleteByKey/'+id,
					method: 'post',
					success:function(ret){
						if(ret.status==200){
							addressWin.close();
							delWarn.close();
							editAddress();
						}
					}
				});
			},
			'取消' : function(){
				delWarn.close();
			}
		}
	});
	delWarn.show();
}

var updateDefaultById = function(_this){
	console.log($(_this).attr("addr_info"));
	var updateWarn = jqueryAlert({
		'title'   : '系统提示',
		'content' : "是否设置为默认地址？" ,
		'modal'   : true,
		'contentTextAlign' : 'left',
		'animateType' : 'linear',
		'buttons' :{
			'确定' : function(){
				$.ajax({
					contentType: 'application/x-www-form-urlencoded',
					url: '${request.contextPath}/cart/address/updateDefaultById/',
					method: 'post',
					data : {
						id : $(_this).attr("addr_id") 
					},
					success:function(ret){
						if(ret.status==200){
							$("#p_addr").text($(_this).attr("addr_info"));
							updateWarn.close();
							addressWin.close();
							editAddress();
							jqueryAlert({
								'icon'    : '${request.contextPath}/cart/alert/img/right.png',
								'content' : '设置成功',
								'closeTime' : 2000,
							}).show();
						}
					}
				});
			},
			'取消' : function(){
				delWarn.close();
			}
		}
	});
	updateWarn.show();
}
</script>
